import { AdminGuard } from './admin.guard'
import { UserService } from '../user/user.service'
import { Reflector } from '@nestjs/core'
import { ExecutionContext } from '@nestjs/common'
import { Request } from 'express'
import { User } from '../user/user.entity'

// 角色或本人鉴权：通过req.params.id 获取到该接口的请求数据=>id
export class selfGuard extends AdminGuard {
  constructor(
    protected userService: UserService,
    protected reflector: Reflector
  ) {
    super(userService, reflector)
  }
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // 获取请求对象
    const req = context.switchToHttp().getRequest<Request>()
    //通过用户名获取用户信息
    const user = await this.userService.find((req.user as User).username)
    // 判断是否为本人
    const requestedId = Number(req.params.id || req.query.id)
    // console.log('🚀 ~ selfGuard ~ canActivate ~ requestedId:', requestedId)
    if (requestedId && requestedId === user?.id) return true
    // 调用父类的 canActivate 方法进行角色判断,
    const canAccess = await super.canActivate(context)
    //如果不是本人, 执行原 AdminGuard 的角色权限检查
    return canAccess
  }
}
